const express = require('express')
const fs = require('fs')

const app = express()

// 使用内置中间件配置静态服务器
// app.use(express.static('public'))

// 使用自定义中间件配置静态服务器
function myStatic(dir) {
    return (req, res, next) => {
        let path = req.path
        if (path == '/') {
            path = '/index.html'
        }
        const filePath = __dirname + '/' + dir + path
        console.log(filePath)
        fs.readFile(filePath, (error, data) => {
            console.log(111)
            if (error) {
                next()
            } else {
                res.end(data)
            }
        })
    }
}

app.use(myStatic('public'))

app.use(express.urlencoded({extended:false}))
app.use(express.json())


// 注册get路由
app.get('/middleware', (req, res) => {
    res.send('middleware respone')
})

app.post('/middleware', (req, res) => {
    const {b, c} = req.body
    console.log('请求参数', b, c)

    res.send('post middleware response')
})



app.listen('9999', () => {
    console.log('服务在9999端口上运行。。。')
})